package com.education.ai.interceptor;

import com.education.ai.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 教师ID拦截器，用于在处理请求前获取当前登录教师的ID
 */
@Component
public class TeacherIdInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(TeacherIdInterceptor.class);
    
    @Autowired
    private AuthService authService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中提取Token
        String token = request.getHeader("Authorization");
        
        if (token != null && !token.isEmpty()) {
            String teacherId = authService.getUserIdFromToken(token);
            
            if (teacherId != null) {
                // 将教师ID存入请求属性中，供后续使用
                request.setAttribute("teacherId", teacherId);
                logger.debug("当前请求关联的教师ID: {}", teacherId);
            } else {
                logger.debug("请求中的token无效或已过期");
            }
        } else {
            logger.debug("请求中未包含Authorization头信息");
        }
        
        // 继续处理请求
        return true;
    }
} 